package com.ec.file.controller;

import cn.hutool.core.io.FileUtil;
import com.aliyun.oss.OSSException;
import com.ec.core.common.core.api.ResponseMsg;
import com.ec.core.common.core.api.Result;
import com.ec.file.common.enums.RespResultEnum;
import com.ec.file.props.FileUploadProperties;
import com.ec.file.service.IOssService;
import com.ec.file.vo.UploadResultVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 文件上传
 *
 * @author Eric Lee
 * @since 2022-07-31 12:41
 */
@Slf4j
@RestController
@RequestMapping("file")
public class FileUploadController {

    @Autowired
    private FileUploadProperties properties;
    @Autowired
    private IOssService ossService;
    /**
     * 默认路径，必须 "/" 结尾
     */
    private final String defaultPath = System.getProperty("user.dir") + "/upload/";

    @PostMapping(value = "upload")
    public Result<List<UploadResultVO>> fileUpload(@RequestParam("file") MultipartFile... files) {
        if (files == null || files.length < 1) {
            return ResponseMsg.error(RespResultEnum.UPLOAD_FILE_COUNT_ERROR);
        }
        List<UploadResultVO> urls = new ArrayList<>();
        for (MultipartFile file : files) {
            String filename = file.getOriginalFilename();
            String uploadUrl = "";
            try {
                if (StringUtils.isNotBlank(filename)) {
                    uploadUrl = fileUpload(file);
                    if (StringUtils.isBlank(uploadUrl)) {
                        return ResponseMsg.error();
                    }
                    urls.add(new UploadResultVO(filename, uploadUrl));
                } else {
                    return ResponseMsg.error(RespResultEnum.UPLOAD_FILE_TYPE_ERROR);
                }
            } catch (OSSException ossEx) {
                log.error("阿里云上传异常：{}", ossEx.getMessage());
                return ResponseMsg.error(RespResultEnum.UPLOAD_OSS_ERROR);
            } catch (Exception e) {
                log.error("文件上传到本地文件异常：{}", e.getMessage());
                return ResponseMsg.error(RespResultEnum.UPLOAD_LOCAL_ERROR);
            }
        }
        return ResponseMsg.success(urls);
    }

    private String fileUpload(MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename();
        boolean flag = false;
        String uploadUrl;
        String suffixName = filename.substring(filename.lastIndexOf(".")).replace(".", "");
        String[] allow = properties.getAllowUpload().split(",");
        for (String al : allow) {
            if (al.equals(suffixName)) {
                flag = true;
                break;
            }
        }
        if (!flag) {
            return "";
        }
        File path = new File(defaultPath);
        if (!path.exists()) {
            path.mkdir();
        }
        String locPath = ossService.fileUpload2Local(file, defaultPath, properties.getIsRenameLocalFile());
        if (properties.getIsUploadOss()) {
            File newFile = new File(locPath);
            uploadUrl = ossService.fileUpload2Oss(newFile, properties.getIsRenameOssFile());
            if (properties.getIsDeleteSource()) {
                FileUtils.deleteQuietly(newFile);
            }
            return properties.getUrl() + uploadUrl;
        } else {
            return properties.getUrl() + FileUtil.getName(locPath);
        }
    }
}
